var map, drawController;
var vectorLayer;
var WGS_PROJECTION = new OpenLayers.Projection("EPSG:4326");
var SPHERICAL_MERCATOR_PROJECTION = new OpenLayers.Projection("EPSG:900913");
var styleMap;
var singleSelectControl, multipleSelectControl;
var rules = new Array();
var tolerance = 400;

function init() {
    
	var defaultStyle = new OpenLayers.Style({
        label: '${num_points}',
        fontColor: '#fff',
        fontFamily: 'arial, sans-serif',
        fontSize: '20px',
        fontWeight: 'bold',
        graphicZIndex: 1,
        pointRadius: '${point_radius}', 
        strokeColor: '#fff',
		strokeWidth: 2.5,
        fillColor: '${color}', 
        fillOpacity: '${severity}',
        cursor: 'pointer'
    },{
        context: {
            num_points: function(feature){
                if(feature.attributes.count > 1)
                    return feature.attributes.count;
                else{
                    return '';
                }
            },
            point_radius: function(feature){ 
                if(feature.attributes.count > 1)
                    return 10*(feature.attributes.count);
                else{
                    return 10;
                }
            } 
        }
    });

	var selectStyle = new OpenLayers.Style({
		'strokeColor': '#1307f1'
	});

	styleMap = new OpenLayers.StyleMap({
		'default': defaultStyle,
		'select': selectStyle
	});
	
	vectorLayer = new Array();

	//MAP
	map = new OpenLayers.Map("map", {
		controls: [],
		displayProjection: WGS_PROJECTION,
		restrictedExtent: new OpenLayers.Bounds(116.27, 4.39, 127, 21.53).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION)
	});
    var osm = new OpenLayers.Layer.Google('Google Map Layer', {numZoomLevels: 20});

	map.addLayers([osm]);
	singleSelectControl = new OpenLayers.Control.SelectFeature(
		vectorLayer,
		{
			displayClass: "singleSelect",
			title: 'Select single or multiple points. To select multiple points, hold shift key',
			clickout: true, toggle: true,
			multiple: false, hover: false,
			toggleKey: "ctrlKey",
			multipleKey: "shiftKey",
			box: false
		}
	);
	multipleSelectControl = new OpenLayers.Control.SelectFeature(
		vectorLayer,
		{
			displayClass: "multipleSelect",
			title: 'Select single or multiple points. To select multiple points, hold shift key',
			clickout: true, toggle: false,
			multiple: false, hover: false,
			toggleKey: "ctrlKey",
			multipleKey: "shiftKey",
			box: true
		}
	);
    
    //PANEL
	var zoomBox = new OpenLayers.Control.ZoomBox(
		{title:"Zoom box: Selecting it you can zoom on an area by clicking and dragging."});

	var zoomMax = new OpenLayers.Control.ZoomToMaxExtent({title:"Zoom to the max extent"});

	var mouseDefaults =  new OpenLayers.Control.MouseDefaults({
		title:'Default mouse configuration'
	});

	var panel = new OpenLayers.Control.Panel();
	panel.addControls([mouseDefaults, singleSelectControl, multipleSelectControl, zoomBox, zoomMax]);
	map.addControl(panel);

    drawController = new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.Point, {featureAdded: onFeatureAdded});
	map.addControls(drawController);
	map.addControl(new OpenLayers.Control.MousePosition());

	map.setCenter(new OpenLayers.LonLat(121.06850, 14.64866).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION), 15);
}

function defineFeature(feature) {
	if( feature.cluster ){
        total = 0;
        size = feature.cluster.length;
        for(i=0; i<size; i++) {
            total += parseInt(feature.cluster[i].attributes.index);
        }
        index_max = Math.round(feature.cluster[0].attributes.index/feature.cluster[0].attributes.severity);
        severity = parseFloat((total/size)/index_max)
        feature.attributes.title = feature.cluster[0].attributes.deployment_id;
        feature.attributes.description = size + " reports in this cluster";
        feature.attributes.index_name = "";
        feature.attributes.color = feature.cluster[0].attributes.color;
        feature.attributes.severity = severity;
        feature.layer.styleMap.styles.default.defaultStyle.fontSize = 15*size;
    }
}

//detail.html
function setMapCenter(lon, lat){
	 map.setCenter(new OpenLayers.LonLat(lon, lat).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION), 17);
}

//home.html
function addLayer(layerName){
	var layer = new OpenLayers.Layer.Vector(layerName, {
		styleMap: styleMap,
		rendererOptions: {zIndexing: true},
		preFeatureInsert: defineFeature,
		strategies: [new OpenLayers.Strategy.Cluster({threshold: 2, distance: 30})]
	});
	layer.styleMap = styleMap;
	
	//@home.html WHEN REPORTS ARE SELECTED, WRITES IN SIDEBAR
	layer.events.register('featureselected', this, on_select_feature);
	layer.events.register('featureunselected', this, on_unselect_feature);

	vectorLayer[layerName] = layer;
	map.addLayers([vectorLayer[layerName]]);
	
	var layers=new Array();
	var i = 0;
	for(x in vectorLayer)
	{
		layers.push(vectorLayer[x]);
		i=i+1;
	}
	singleSelectControl.setLayer(layers);
	multipleSelectControl.setLayer(layers);
}

//home.html
function on_select_feature(event){
    //get_number_of_nearby_points(event.feature.attributes.deployment_id, event.feature.geometry);
    text = "";
    text += 
        '<div class="post"><h3 class="title"><a href="/reports/' + event.feature.attributes.title.split(' ').join('').toLowerCase() + '/">' + event.feature.attributes.title +
        '</a></h3><div class="entry">' +
        event.feature.attributes.description +
        '<br />';
    
    if(event.feature.attributes.index_name){
        text += event.feature.attributes.index_name + ': ' + event.feature.attributes.index_level_name;
    }
    text += '</div></div>';
    $("#report_board").append(text);  
}

//home.html
function on_unselect_feature(event){
    var info_div = document.getElementById('report_board');
    info_div.innerHTML = '';
}

//in home.html
function get_reports(reports, layerName) {
	var format = new OpenLayers.Format.GeoJSON({internalProjection: SPHERICAL_MERCATOR_PROJECTION, externalProjection: WGS_PROJECTION});
    vectorLayer[layerName].removeAllFeatures();
	vectorLayer[layerName].addFeatures(format.read(reports));
}

//needed in submit
function onFeatureAdded(feature){
    vectorLayer.removeAllFeatures();
    vectorLayer.addFeatures(feature);
    mapPoint = new OpenLayers.Geometry.Point(feature.geometry.getBounds().getCenterLonLat().lon, feature.geometry.getBounds().getCenterLonLat().lat).transform(SPHERICAL_MERCATOR_PROJECTION, WGS_PROJECTION);
    lon = mapPoint.x;
    lat = mapPoint.y;
}

//in submit
function add_point(){
    var mapPoint = new OpenLayers.Geometry.Point(lon , lat).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION);
    var newpoint = new OpenLayers.Feature.Vector(mapPoint, {description: desc, title: title, index: index});
    vectorLayer.addFeatures(newpoint);
}

//submit.html
function activateDrawFeature(){
	drawController.activate();
}

function get_number_of_nearby_points(layername, point){
    rating = 0;
    
    for(var i=0; i<map.layers.length; i++){
        if  (map.layers[i].name == layername)
            layer = map.layers[i]
    }
    
    features = layer.features;
    points = new Array();
    
    for(var i=0; i<features.length; i++){
        points.push(features[i].geometry);
    }
    
    for(var i=0; i<points.length; i++){
        distance = point.distanceTo(points[i])
        if(distance!=0 && distance <= tolerance)
            rating++;
    }
    alert(rating);
}

